package com.letu.mq.util;

import com.letu.cache.repository.CachePlusOps;
import com.letu.core.context.ContextUtil;
import com.letu.core.rocketmq.MqCacheKeyBuilder;
import com.letu.mq.model.MySimpleMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MessageExtUtil {
    @Autowired
    private CachePlusOps cachePlusOps;

    public boolean isUseMessage(MySimpleMessage mySimpleMessage) {
        if (mySimpleMessage != null) {
            try {
                Map<String, Object> headerMap = mySimpleMessage.getHeaders();
                String key = headerMap.get("key").toString();
                //唯一业务key 用于幂等
                Integer i = cachePlusOps.get(new MqCacheKeyBuilder().hashKey(key));
                if (i != null && i == 1) {
                    return false;
                }
            } catch (Exception exx) {
//                exx.printStackTrace();
                return true;
            }
        }
        return true;
    }

    public void removeKey(MySimpleMessage mySimpleMessage) {
        if (mySimpleMessage != null) {
            //唯一业务key 用于幂等
            try {
                Map<String, Object> headerMap = mySimpleMessage.getHeaders();
                String key = headerMap.get("key").toString();
                cachePlusOps.del(new MqCacheKeyBuilder().hashKey(key));
            } catch (Exception exx) {
                exx.printStackTrace();
            }

        }
    }


    /**
     * 组装key和 系统共享数据，如用户id，项目id
     *
     * @param mySimpleMessage
     */
    public void assembleHeader(MySimpleMessage mySimpleMessage) {
        Map<String, Object> headerMap = mySimpleMessage.getHeaders();
        String key = MessageKeyUtil.assembleKey();
        headerMap.put("key", key);
        mySimpleMessage.setHeaders(headerMap);
    }

}
